package com.labichaoka.chaoka.ui.account;

import com.labichaoka.chaoka.base.MyApplication;
import com.labichaoka.chaoka.entity.BaseResponse;
import com.labichaoka.chaoka.entity.LoginRequest;
import com.labichaoka.chaoka.entity.LoginResponse;
import com.labichaoka.chaoka.entity.SendCodeRequest;
import com.labichaoka.chaoka.net.BaseSubscriber;
import com.labichaoka.chaoka.net.DataManager;
import com.labichaoka.chaoka.utils.SharedPreferencesManager;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by ruan on 2018/7/31.
 */

public class LoginInteractorImpl implements LoginInteractor {
    private DataManager manager = new DataManager(MyApplication.mContext);
    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();

    @Override
    public void getSmsCode(SendCodeRequest request, OnFinishedListener listener) {
        mCompositeSubscription.add(manager.getSmsCode(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseResponse>() {
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        listener.onGetCodeFailed();
                    }

                    @Override
                    public void onNext(BaseResponse response) {
                        listener.onGetCodeSuccess(response);
                    }
                })

        );

    }

    @Override
    public void login(LoginRequest request, OnFinishedListener listener) {
        mCompositeSubscription.add(manager.login(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<LoginResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        listener.onLoginFailed();
                    }

                    @Override
                    public void onNext(LoginResponse response) {
                        SharedPreferencesManager.getInstance().putString("phone", request.getLoginPhone());
                        listener.onLoginSuccess(response);
                    }
                })


        );
    }
}
